package electsys;


import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;


/**
 *
 * @author XiaoR
 */
public class Client {
    HttpClient httpclient = null;
    //Cookie[] cookies = null;

    public Client(){
        httpclient = new HttpClient();
    //    httpclient.getHostConfiguration().setProxy("127.0.0.1", 8888);
    }
    public synchronized String getHtml(String url) {
        GetMethod httpget;
        try {
            httpget = new GetMethod(url);
            httpget.setFollowRedirects(true);
            httpclient.executeMethod(httpget);
            //return httpget.getResponseBodyAsString();
            //System.out.println(httpclient.getParams().getCookiePolicy());
            //cookies = httpclient.getState().getCookies();

            return MyUtil.getStringFromStream(httpget.getResponseBodyAsStream(), httpget.getResponseCharSet());
        }
        catch (HttpException ex) {
           Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
           Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

        }
        return null;
    }

    public synchronized String postHtml(String url, NameValuePair[] nvps) {
        PostMethod httpost;
        try {
            httpost = new PostMethod(url);
            httpost.addRequestHeader("Referer", MyConst.ROOT);
            httpost.addRequestHeader("Origin", MyConst.SITE);
            httpost.setFollowRedirects(false);
            if (nvps != null) httpost.addParameters(nvps);
            //System.out.println("toString:" + httpost.getRequestLine());
            httpclient.executeMethod(httpost);
            //return httpost.getResponseBodyAsString();
            return MyUtil.getStringFromStream(httpost.getResponseBodyAsStream(), httpost.getResponseCharSet());
        } catch (HttpException ex) {
           Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex){
           Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
        
        }
        return null;
    }


}
